package com.xydtech.common.token;

import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.cache.EhcacheUtil;
import com.xydtech.common.constant.MiniProgramConstants;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.spring.SpringUtils;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 微信小程序/微信公众号Token工具类，说明下：为什么要放在这里，因为APP那边要生成小程序的二维码和电子名片的二维码，但又不确保这几个项目
 * 会同时上线，因此只能放在工具类中
 * @author Daniel
 * @date 2022/2/8 15:17
 */

public class WechatTokenUtil {

    private static final Logger logger = LoggerFactory.getLogger(WechatTokenUtil.class);
    private static CacheManager cacheManager = SpringUtils.getBean(CacheManager.class);

    /**
     * 获取微信小程序（快贷）的access_token
     * @param appId 小程序唯一凭证，即 AppID
     * @param appSeret 小程序唯一凭证密钥
     * @param appleSendUrl 小程序接口地址
     * @return java.lang.String
     * @exception
     * @author Daniel
     * @date 2022/2/8 15:31
     */
    public static String getQucikLoanMiniProgramAccessToken(String appId, String appSeret, String appleSendUrl, String tokenUrl) {

        /**
         * 首先从缓存中拿取，看下是否存在，如果不存在的时候，再请求
         */
        String accessTokenKey = MiniProgramConstants.QUICK_LOAN_MINIPROGRAM_ACCESSTOKEN + appId;
        String quickLoanMiniProgramAccessToken = EhcacheUtil.getQuickLoanMiniProgramAccessToken(accessTokenKey, cacheManager);
        if (!StringUtils.isEmpty(quickLoanMiniProgramAccessToken)) {
            return quickLoanMiniProgramAccessToken;
        }

        //改为调用bigdata
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("appId",appId);
        map.add("appSeret",appSeret);
        map.add("appleSendUrl",appleSendUrl);
        String apiUrl = tokenUrl + "/api/token/getWxAccessToken";
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
        JSONObject jsonObject = new RestTemplate().postForObject(apiUrl, httpEntity, JSONObject.class);
        if (StringUtils.objIsNullOrEmpty(jsonObject.getString("accessToken"))) {
            //因为返回正常的时候，是没有
            return null;
        } else {
            quickLoanMiniProgramAccessToken = jsonObject.getString("accessToken");
            //加入到缓存中
            EhcacheUtil.setQuickLoanMiniProgramAccessToken(accessTokenKey, quickLoanMiniProgramAccessToken, cacheManager);
        }
        return quickLoanMiniProgramAccessToken;
    }

    /**
     * 获取电子名片access_token
     * @return
     */
    public static String getEcardMiniProgramAccessToken(String appId, String secret, String appleSendUrl, String tokenUrl) {

        /**
         * 思路：
         * 1. 首先看下缓存中是否存在access_token，如果存在，那么直接从缓存中获取，并返回
         * 2. 如果不存在，那么请求微信的接口获取对应的access_token，然后放入缓存
         *  2.1 首先查询数据库获取appid和secret
         *  2.2 通过appid和secret获取access_token
         *  2.3 放入缓存中
         */
        String accessTokenKey = MiniProgramConstants.ECARD_MINIPROGRAM_ACCESSTOKEN + appId;
        String ecardAccessToken = EhcacheUtil.getEcardMiniprogramAccessToken(accessTokenKey, cacheManager);
        if (!StringUtils.isEmpty(ecardAccessToken)) {
            return ecardAccessToken;
        }

        //改为调用bigdata
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("appId",appId);
        map.add("appSeret",secret);
        map.add("appleSendUrl",appleSendUrl);
        String apiUrl = tokenUrl + "/api/token/getWxAccessToken";
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
        JSONObject jsonObject = new RestTemplate().postForObject(apiUrl, httpEntity, JSONObject.class);
        if (StringUtils.objIsNullOrEmpty(jsonObject.getString("accessToken"))) {
            //因为返回正常的时候，是没有
            return null;
        } else {
            ecardAccessToken = jsonObject.getString("accessToken");
            //加入到缓存中
            EhcacheUtil.setQuickLoanMiniProgramAccessToken(accessTokenKey, ecardAccessToken, cacheManager);
        }

        return ecardAccessToken;
    }


}
